package cn.growthgate.fgo.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.apache.commons.text.StringEscapeUtils;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.enums.IEnum;

/**
 * 字符串工具类
 * 
 * @author GrowthGate
 * @since 2019年3月27日
 *
 */
public class StringUtils extends org.apache.commons.lang3.StringUtils {

	public static String getRandomUUID() {
		return UUID.randomUUID().toString().replace("-", "");
	}
	
	public static Integer[] splitToInteger(String str, String separatorChars) {
		String[] strArray = split(str, separatorChars);
		if (strArray == null) {
			return null;
		}
		Integer[] array = new Integer[strArray.length];
		for (int i = 0; i < strArray.length; i++) {
			array[i] = Integer.parseInt(strArray[i]);
		}
		return array;
	}
	
	public static <E extends IEnum> E[] splitToEnum(Class<E> enumClass, String str, String separatorChars) {
		String[] strArray = split(str, separatorChars);
		if (strArray == null) {
			return null;
		}
		List<E> list = new ArrayList<E>(strArray.length);
		for (String string : strArray) {
			E e = EnumUtils.getByValue(enumClass, Integer.parseInt(string));
			list.add(e);
		}
		return CollectionUtils.toArray(list, enumClass);
	}

	public static String toJson(Object object) {
		return JSON.toJSONString(object);
	}

	/**
	 * html转义
	 * @param str
	 * @return
	 */
	public static String toHtml(String str) {
		return StringEscapeUtils.escapeHtml4(str);
	}

	/**
	 * 压缩字符串
	 * @param str
	 * @return
	 */
	public static String zip(String str) {
		if (isEmpty(str)) {
			return str;
		}
		// 转为url字符串（为了剔除中文字符）
		str = UrlUtils.encode(str);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		try (GZIPOutputStream gzipos = new GZIPOutputStream(baos)) {
			gzipos.write(str.getBytes());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return Base64.encodeBase64String(baos.toByteArray());
	}

	/**
	 * 解压缩字符串
	 * @param str
	 * @return
	 */
	public static String unzip(String str) {
		if (isEmpty(str)) {
			return str;
		}
		byte[] bytes = Base64.decodeBase64(str);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
				GZIPInputStream gzipis = new GZIPInputStream(bais)) {
			IOUtils.copy(gzipis, baos);
		} catch (IOException e) {
			e.printStackTrace();
		}
		str = baos.toString();
		// 转回中文字符串
		return UrlUtils.decode(str);
	}

}
